﻿using Cxuu.Models;
using Cxuu.Service;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;


namespace Cxuu.Web.Admin
{
    public class Base : Controller
    {
        public Base()
        {

        }
        /// <summary>
        /// 判断用户操作权限
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            ViewAdminUser adminUser = await UserClaims();

            if (adminUser.Gid == 1)
            {
                ViewBag.sr = null;//设置为1 超级管理员，不受功能权限限制！
                await base.OnActionExecutionAsync(context, next);
            }
            else
            {
                var userGroupInfo = await UserGroupInfoAsync(context, adminUser.Gid);
                List<string> systemRole = JsonSerializer.Deserialize<List<string>>(userGroupInfo.Systemrole.ToLower());
                ViewBag.sr = systemRole;
                string controllerName = RouteData.Values["controller"].ToString().ToLower();
                string actionName = RouteData.Values["action"].ToString().ToLower();
                if (systemRole.Exists(x => x == controllerName + "_" + actionName))
                    await base.OnActionExecutionAsync(context, next);
                else
                    context.Result = Json(new { status = 0, msg = "没有权限操作此功能！" });
            }

        }

        /// <summary>
        /// 登录用户信息 COOKIE
        /// </summary>
        /// <returns></returns>

        public async Task<ViewAdminUser> UserClaims()
        {
            var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            ViewAdminUser adminUser = new();
            if (result.Succeeded)
            {
                adminUser.Id = int.Parse(result.Principal.FindFirst("id").Value);
                adminUser.Gid = int.Parse(result.Principal.FindFirst("gid").Value);
                adminUser.Username = result.Principal.FindFirst("username").Value;
                adminUser.Nickname = result.Principal.FindFirst("nickname").Value;
                adminUser.Loginip = result.Principal.FindFirst("loginip").Value;
                adminUser.Logintime = Convert.ToDateTime(result.Principal.FindFirst("logintime").Value);
                return adminUser;
            }
            else
            {
                return null;
            }

        }


        public async Task<AdminUserGroup> UserGroupInfoAsync(ActionExecutingContext context, int userGid)
        {
            var _adminUserGroupService = context.HttpContext.RequestServices.GetService<AdminUserGroupService>();
            return await _adminUserGroupService.GetAsync(userGid);
        }


        public async Task<UserInfo> UserInfoAsync()
        {
            ViewAdminUser adminUser = await UserClaims();
            UserInfo userInfo = new();
            userInfo.Id = adminUser.Id;
            userInfo.Gid = adminUser.Gid;
            userInfo.Username = adminUser.Username;
            userInfo.Controller = RouteData.Values["controller"].ToString().ToLower();
            userInfo.Action = RouteData.Values["action"].ToString().ToLower();
            userInfo.Ip = Request.HttpContext.Connection.RemoteIpAddress.ToString();
            //userInfo.Ip = WebUtility.GetAddressIP();
            return userInfo;
        }


    }
}
